/**
 * 
 */
package uk.co.sapereaude.prometheus.core;

import java.io.FileInputStream;
import java.io.IOException;

import alice.tuprolog.InvalidTheoryException;
import alice.tuprolog.MalformedGoalException;
import alice.tuprolog.NoSolutionException;
import alice.tuprolog.Prolog;
import alice.tuprolog.SolveInfo;
import alice.tuprolog.Theory;
import alice.tuprolog.UnknownVarException;

/**
 * @author Kieran O'Neill
 */
public class PrometheusCore {
	
    private static final String PROMETHEUS_CORE_PROLOG_FILE = "//prolog//prometheuscore.pl";
    private static final String LIB_PROLOG_FILE = "//prolog//pl_lib.pl";
    private static final String KNOWLEDGEBASE_PROLOG_FILE = "//prolog//knowledgebase//knowledgebase.p";
    
    // Queries.
    private static final String RESPONSE_TERM  = "Response";
    
    /**
	 * Constructor
	 */
	public PrometheusCore() {
		super();
		// TODO: create log file stuff.
	}
	
	/**
	 * Returns the name of the Prolog's core filename.
	 * 
	 * @return	name of the core Prolog file.
	 */
	public String getCoreFilename() {
		return PROMETHEUS_CORE_PROLOG_FILE;
	}
	
	/**
	 * The string provided by {@code message} is passed to the Prolog core and a response is
	 * returned as a string. The Prolog core file is first consulted.
	 * 
	 * @param		message		a String that is passed to Prolog.
	 *  
	 * @return 	a String passed from Prolog. 
	 * @throws MalformedGoalException 
	 */
	public String getResponse(String message)
	{
		String response = null;
		
		// Initiate the Prolog engine.
		Prolog prologEngine = new Prolog();
		
		Theory prometheusCore = null;
		Theory prologLib = null;
		Theory knowledgeBase = null;
		
		// Setup the Theories with the Prolog files.
		try 
		{
			prometheusCore = new Theory(new FileInputStream(System.getProperty("user.dir") + PROMETHEUS_CORE_PROLOG_FILE));
			prologLib = new Theory(new FileInputStream(System.getProperty("user.dir") + LIB_PROLOG_FILE));
			knowledgeBase = new Theory(new FileInputStream(System.getProperty("user.dir") + KNOWLEDGEBASE_PROLOG_FILE));
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		// Load the prolog files into the Prolog engine.
		try 
		{
			prologEngine.setTheory(prometheusCore);
			prologEngine.addTheory(prologLib);
			prologEngine.addTheory(knowledgeBase);
		} 
		catch (InvalidTheoryException e) 
		{
			e.printStackTrace();
		}
		
		SolveInfo answer = null;
		
		try 
		{
			answer = prologEngine.solve("prometheus(" + message + ", Response).");
		} 
		catch (MalformedGoalException e) 
		{
			e.printStackTrace();
		}
		
		try 
		{
			response = answer.getTerm(RESPONSE_TERM).toString();
		} 
		catch (NoSolutionException e) 
		{
			e.printStackTrace();
		} 
		catch (UnknownVarException e) 
		{
			e.printStackTrace();
		}
		
		return response;
	}
}
